﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;

namespace InForTheCloud.OAuthLite
{
    public static class OAuthRequestHelper
    {
        public static T OAuthRequest<T>(this T request, OAuthSecret oauthSecret)
            where T: WebRequest
        {
            OAuthBaseStringBuilder builder = new OAuthBaseStringBuilder();
            builder.method(request.Method)
                .host(request.RequestUri.Host)
                .scheme(request.RequestUri.Scheme);

            var queryStart = request.RequestUri.PathAndQuery.IndexOf('?');
            if (queryStart > 0)
            {
                builder.path(request.RequestUri.PathAndQuery.Substring(0, queryStart));
            }
            else
            {
                builder.path(request.RequestUri.PathAndQuery);
            }

            if (!string.IsNullOrEmpty(request.RequestUri.Query))
            {
                string[] query = request.RequestUri.Query.Substring(1).Split('&');

                foreach (var queryPart in query)
                {
                    var paramParts = queryPart.Split('=');
                    builder.query(Uri.UnescapeDataString(paramParts[0]), paramParts.Length > 1 ? Uri.UnescapeDataString(paramParts[1]) : string.Empty);
                }
            }

            builder.oauth_consumer_key(oauthSecret.ConsumerKey)
                .oauth_nonce(Guid.NewGuid().ToString("D"))
                .oauth_signature_method_HMAC_SHA1()
                .oauth_timestamp(Convert.ToInt32(DateTime.Now.Subtract(new DateTime(1970, 1, 1)).TotalSeconds));
            if (oauthSecret.HasToken())
                builder.oauth_token(oauthSecret.Token);

            string signature = oauthSecret.SignHMACSHA1(builder.ToString());

            request.Headers["Authorization"] = builder.ToHeader(signature);

            return request;
        }
        
    } 
}
